package com.koron.order.LineHomepage.controller;

import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.system.SystemCacheUtil;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.StringUtils;
import com.koron.order.LineHomepage.bean.VO.*;
import com.koron.order.LineHomepage.bean.dto.LineEquipmentDTO;
import com.koron.order.LineHomepage.bean.dto.LineKeyRiskDTO;
import com.koron.order.LineHomepage.bean.dto.LineRiskDTO;
import com.koron.order.LineHomepage.bean.query.DefectReportQuery;
import com.koron.order.LineHomepage.bean.query.LineEquipmentQuery;
import com.koron.order.LineHomepage.bean.query.RiskReportQuery;
import com.koron.order.LineHomepage.service.LineHomePageService;
import com.koron.order.overhaul.bean.dto.Equipment;
import com.koron.order.risk.base.bean.query.LineKeyRiskQuery;
import com.koron.order.risk.base.bean.query.LineRiskQuery;
import com.koron.order.risk.base.bean.vo.LineKeyRiskVO;
import com.koron.order.risk.base.bean.vo.LineRiskVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @ClassName: LineHomePageController
 * @Description:
 * @Date: 2023/2/15
 * @Author: 李一辰
 * @Version: 1.0
 **/
@Slf4j
@Api(tags = "输电风控首页")
@RestController
@RequestMapping("/lineHome")
public class LineHomePageController {

    @Autowired
    private LineHomePageService lineHomePageService;

    //
    private final ExecutorService service = Executors.newFixedThreadPool(4);

    private EamUser getCurr() {
        return ThreadLocalContext.get();
    }

    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    private String getDeptId() {
        EamUser eamUser = getCurr();
        return eamUser.getDeptId();
    }


    private Boolean isWaterManagerDept(String orgId) {
        OrgBean orgBean = SystemCacheUtil.queryDeptByOrgId(orgId);
        return orgBean != null && orgBean.getName().endsWith("管理部");
    }

    private Map<String, Object> statistic() {
        CountDownLatch latch = new CountDownLatch(4);
        HashMap<String, Object> result = new HashMap<>();
        service.execute(() -> {
            try {
                Integer defectCount = getDefectCount();
                result.put("defectCount", defectCount);
            } finally {
                latch.countDown();
                ThreadLocalContext.clear();
            }
        });
        service.execute(() -> {

            try {
                Integer riskCount = getRiskCount();
                result.put("riskCount", riskCount);
            } finally {
                latch.countDown();
                ThreadLocalContext.clear();
            }
        });
        service.execute(() -> {

            try {
                AnnualTripVO lineTripQuarter = getLineTripQuarter();
                result.put("lineTripQuarter", lineTripQuarter);
            } finally {
                latch.countDown();
                ThreadLocalContext.clear();
            }
        });
        service.execute(() -> {
            try {
                AnnualTripVO lineTripAnnual = getLineTripAnnual();
                result.put("lineTripAnnual", lineTripAnnual);
            } finally {
                latch.countDown();
                ThreadLocalContext.clear();
            }
        });

        return result;
    }


    private Map<String, Object> statis() {
        HashMap<String, Object> map = new HashMap<>();
        Integer defectCount = getDefectCount();
        map.put("defectCount", defectCount);
        Integer riskCount = getRiskCount();
        map.put("riskCount", riskCount);
        AnnualTripVO lineTripQuarter = getLineTripQuarter();
        map.put("lineTripQuarter", lineTripQuarter);
        AnnualTripVO lineTripAnnual = getLineTripAnnual();
        map.put("lineTripAnnual", lineTripAnnual);
        return map;
    }

    @ApiOperation("缺陷数量查询(暂时不做权限限制)")
    public Integer getDefectCount() {
        List<LineDefectVO> defectList = ADOConnection.runTask(getCurrDs(), lineHomePageService, "getDefectCount", List.class);
        return defectList.size();
    }

    @ApiOperation("风险点数查询(暂时不做权限限制)")
    public Integer getRiskCount() {
        return ADOConnection.runTask(getCurrDs(), lineHomePageService, "getRiskCount", Integer.class);
    }

    @ApiOperation("线路跳闸记录(季度)")
    public AnnualTripVO getLineTripQuarter() {
        return ADOConnection.runTask(getCurrDs(), lineHomePageService, "getLineTripQuarter", AnnualTripVO.class);
    }

    @ApiOperation("线路跳闸记录(年度)")
    public AnnualTripVO getLineTripAnnual() {
        return ADOConnection.runTask(getCurrDs(), lineHomePageService, "getLineTripAnnual", AnnualTripVO.class);
    }

    @ApiOperation("统计数据查询")
    @GetMapping("/statistic")
    public Response<Map<String, Object>> statistics() {
        Map<String, Object> statistic = statis();
        return Response.ok(statistic);
    }

    @ApiOperation("风险上报类比")
    @GetMapping("/riskReport")
    public Response<List<RiskReportVO>> riskReport(RiskReportQuery riskReportQuery) {
        List<RiskReportVO> riskReportVOS = ADOConnection.runTask(getCurrDs(), lineHomePageService, "getRiskReportingAnalogy", List.class, riskReportQuery);
        return Response.ok(riskReportVOS);
    }

    @ApiOperation("缺陷上报类比")
    @GetMapping("/defectReport")
    public Response<List<DefectReportVO>> defectReport(DefectReportQuery defectReportQuery) {
        List<DefectReportVO> defectKeys = ADOConnection.runTask(getCurrDs(), lineHomePageService, "getDefectKeys", List.class, defectReportQuery);
        return Response.ok(defectKeys);
    }

    @ApiOperation("缺陷统计")
    @GetMapping("/defectStatistic")
    public Response<DefectStatistic> defectStatistic(@RequestParam(name = "date", required = false) Date date) {
        DefectStatistic defectStatistic = ADOConnection.runTask(getCurrDs(), lineHomePageService, "getDefectStatistic", DefectStatistic.class, date);
        return Response.ok(defectStatistic);
    }

    @ApiOperation("杆塔设备视图")
    @GetMapping("/equipmentList")
    public Response<Map<String, List<Equipment>>> mapVisualization(LineEquipmentQuery lineEquipmentQuery) {
        List<Equipment> allEquipments = ADOConnection.runTask(getCurrDs(), lineHomePageService, "list", List.class, lineEquipmentQuery);
        if (StringUtils.isNotEmpty(lineEquipmentQuery.getDeptId())) {
            List<Equipment> equipmentList = allEquipments.stream().filter(i -> lineEquipmentQuery.getDeptId().equals(i.getDeptId())).collect(Collectors.toList());
            Map<String, List<Equipment>> map = equipmentList.stream().collect(Collectors.groupingBy(Equipment::getParentName));
            return Response.ok(map);
        }
        Map<String, List<Equipment>> map = allEquipments.stream().collect(Collectors.groupingBy(Equipment::getParentName));
        return Response.ok(map);
    }

    @ApiOperation("杆塔设备视图详情")
    @GetMapping("/selectEquipmentDetail")
    public Response<LineEquipmentDTO> selectEquipmentDetail(String id) {
        LineEquipmentDTO detail = ADOConnection.runTask(getCurrDs(), lineHomePageService, "selectEquipmentDetail", LineEquipmentDTO.class, id);
        return Response.ok(detail);
    }

    @ApiOperation("风险视图")
    @GetMapping("/lineRiskList")
    public Response<List<LineRiskVO>> listRisks(LineRiskQuery lineRiskQuery) {
        List<LineRiskVO> list = ADOConnection.runTask(getCurrDs(), lineHomePageService, "listRisks", List.class, lineRiskQuery);
        return Response.ok(list);
    }
    @ApiOperation("风险视图详情")
    @GetMapping("/selectRiskDetail")
    public Response<LineRiskDTO> selectRiskDetail( String id) {
        LineRiskDTO lineRiskDTO = ADOConnection.runTask(getCurrDs(), lineHomePageService, "selectRiskDetail", LineRiskDTO.class, id);
        return Response.ok(lineRiskDTO);
    }

    @ApiOperation("关键级视图")
    @GetMapping("/lineKeyRiskList")
    public Response<List<LineKeyRiskVO>> listKeyRisks(LineKeyRiskQuery lineRiskQuery) {
        List<LineKeyRiskVO> list = ADOConnection.runTask(getCurrDs(), lineHomePageService, "listKeyRisks", List.class, lineRiskQuery);
        if(StringUtils.isNotEmpty(lineRiskQuery.getKeyLevel())){
            List<LineKeyRiskVO> dtoList = list.stream().filter(i -> lineRiskQuery.getKeyLevel().equals(i.getKeyLevel())).collect(Collectors.toList());
            return Response.ok(dtoList);
        }
        return Response.ok(list);
    }

    @ApiOperation("关键级视图详情")
    @GetMapping("/lineKeyRiskDetail")
    public Response<LineKeyRiskDTO> selectKeyRisks(String id) {
        LineKeyRiskDTO lineKeyRiskDTO = ADOConnection.runTask(getCurrDs(), lineHomePageService, "selectKeyRisks", LineKeyRiskDTO.class, id);
        return Response.ok(lineKeyRiskDTO);
    }

}
